package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.IWechatService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;


@Service
@Slf4j
public class WechatServiceImpl implements IWechatService {

    //    @Value("${wechat.appid}")
    private String appid = "wx04ed0a6acbbaedaa";

    //    @Value("${wechat.secret}")
    private String secret = "d46ce42fd75048a481abd77fb0e997d5";

    private static final String GET_OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";


    private static final String GET_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";


    @Override
    public String getOpenid(String code) {

        HashMap<String, Object> param = new HashMap<>();
        param.put("appid", appid);
        param.put("secret", secret);
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");

        String jsonStr = HttpUtil.get(GET_OPENID_URL, param);
        JSON responJson = JSONUtil.parse(jsonStr);
        log.info("获取openid响应json对象{}", responJson);


        String openid = responJson.getByPath("openid") + "";

        return openid;
    }

    @Override
    public String getPhone(String detailCode) {
        String accessToken = this.getAccessToken();
        HashMap<String, Object> param = new HashMap<>();
        param.put("code", detailCode);
        String responJson = HttpUtil.post(GET_PHONE_URL + accessToken, JSONUtil.toJsonStr(param));
        JSON json = JSONUtil.parse(responJson);

        return json.getByPath("phone_info.phoneNumber") + "";
    }


    private String getAccessToken() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("appid", appid);
        param.put("secret", secret);
        param.put("grant_type", "client_credential");

        String jsonStr = HttpUtil.get(GET_ACCESS_TOKEN_URL, param);
        JSON responJson = JSONUtil.parse(jsonStr);
        String accessToken = responJson.getByPath("access_token") + "";
        return accessToken;
    }
}
